package com.dxd.servlet.swzl;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dxd.entity.Message;
import com.dxd.entity.MessageBoard;
import com.dxd.entity.MessageType;
import com.dxd.entity.PageEntity;
import com.dxd.entity.UserInfo;
import com.dxd.servlet.PublicServlet;

/**
 * 前端首页
 * 
 * @author Administrator
 *
 */
@WebServlet("/swzl/index")
public class IndexServlet extends PublicServlet {
	private static final long serialVersionUID = -1093647922092449357L;
	private static final Logger LOG = LoggerFactory.getLogger(IndexServlet.class);

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String type = request.getParameter("type");
		LOG.info("请求：/swzl/index?type={}", type);
		if ("detail".equals(type)) {
			// 根据id查询信息详情
			String id = request.getParameter("id");
			if (id == null || "".equals(id)) {
				LOG.error("查看信息详情失败，参数id为空");
			}
			Message message = messageDao.queryOne(Integer.parseInt(id));
			List<MessageBoard> messageBoards = null;
			if (message != null && message.getId() != null) {
				messageBoards = messageBoardDao.queryByMessageId(Integer.parseInt(id));
			}
			request.setAttribute("message", message);
			request.setAttribute("messageBoards", messageBoards);
			Dispatcher("/view/swzl/detail.jsp");

		} else {
			// 用户首页信息，搜索关键字
			String searchName = request.getParameter("searchName");
			// 物品类型（手机，钱包......）
			String typeName = request.getParameter("typeName");
			// 时间段（1,2,3,4....）
			String lostTime = request.getParameter("lostTime");
			// 类型父级id：1、失物招领，2寻物启事
			String typeParentId = request.getParameter("typeParentId");
			Integer parentId = null;
			Integer userId = null;
			if (typeParentId != null && !"".equals(typeParentId)) {
				parentId = Integer.parseInt(typeParentId);
				// 表示查询我的发布
				if (parentId == 3) {
					UserInfo userInfo = getUserInfoSwzl();
					if (userInfo != null && userInfo.getId() != null) {
						parentId = null;
						userId = userInfo.getId();
					} else {
						Redirect(request.getContextPath() + "/swzl/userInfo?type=goLogin");
						return;
					}
				}
			}

			// 根据上面的条件查询首页信息
			PageEntity<Message> datas = messageDao.queryList(pageMap.get("page"), 8, parentId, typeName, searchName,
					lostTime, userId);

			// 查询所有的类型名称，用来页面供选择
			List<MessageType> messageTypes = messageTypeDao.queryList();
			request.setAttribute("searchName", searchName);
			request.setAttribute("typeName", typeName);
			request.setAttribute("datas", datas);
			request.setAttribute("lostTime", lostTime);
			request.setAttribute("typeParentId", typeParentId);
			request.setAttribute("messageTypes", messageTypes);
			Dispatcher("/view/swzl/index.jsp");
		}
	}

}